package com.foreveross.common.TaskManager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.foreveross.common.Constants;
import com.foreveross.dao.CommonDAO;
import com.foreveross.util.DateUtil;
import com.foreveross.util.FileUtil;

@Service("commonService")
@Transactional
public class CommonService {
	
	private static Logger log = Logger.getLogger(CommonService.class);
	
	@Resource
	CommonDAO commonDAO;
	
	private Timer timer = null; 
	
	private final Calendar cal = Calendar.getInstance();
	
	//一周运行一次
	private final long timePeriod = 24*60*60*1000*7;
	

	public Timer getTimer() {
		return timer;
	}
	
	public void deleteFilesTimer(){
		timer = new Timer(); 	          
	    timer.schedule(deleteFilesTimerTask(), setTime(), timePeriod); 
	}
	
	private TimerTask deleteFilesTimerTask(){
		return new TimerTask() {
	    	 public void run() {  
	    		 //执行的内容   
	    		 deleteFiles();
	    	 }
	    };
	}

	private Date setTime(){	

		//每天定点执行     
		cal.set(Calendar.HOUR_OF_DAY,00);     
		cal.set(Calendar.MINUTE,30);    
		cal.set(Calendar.SECOND,0);
		
		
		Date date=cal.getTime(); 
		//第一次执行定时任务的时间 
		//如果第一次执行定时任务的时间 小于 当前的时间  
		//此时要在 第一次执行定时任务的时间 加一天，以便此任务在下个时间点执行。如果不加一天，任务会立即执行。  
		if (date.before(new Date()))  date =DateUtil.addDay(date, 1);   
		
		return date;
	}
	
	
	public List<String> getAllImgUrl() throws Exception {
		List<String> list = new ArrayList<String>();
		List<String> urlList =  commonDAO.findAllImgUrl();
		for(String str :urlList){
			String [] urls = str.split(",");
			for(String url : urls){
				String absolutePath = Constants.REAL_PATH+url;
				list.add(absolutePath);
			}
		}
		return list;
	} 
	
	/**
	 * 定时删除文件
	 */
	public void deleteFiles(){
		try{
			List<String> fileUrls = getAllImgUrl();
			FileUtil.deleteFiles(fileUrls);
		}catch(Exception e){
			log.error("定时删除文件失败",e);
			e.printStackTrace();
		}
		
	}
}
